<template>
	<view class="publish-container">
		<view class="nav-placeholder"></view>
		<view class="nav-bar">
			<tn-button style="color: black; width: 35px; height: 35px; font-size: 15px;" :border="false"
				@click="handleReturn">
				<text class="tn-icon-left" />
			</tn-button>
			<text class="title">我发布的</text>
		</view>

		<!-- 搜索框 -->
		<view class="search-box">
			<view class="search-input-box">
				<text class="tn-icon-search"></text>
				<input type="text" 
					v-model="searchKeyword" 
					placeholder="搜索商品名称" 
					confirm-type="search"
					@confirm="handleSearch"
					class="search-input" />
				<text class="tn-icon-close" v-if="searchKeyword" @tap="clearSearch"></text>
			</view>
		</view>

		<!-- 商品列表 -->
		<view class="goods-list">
			<view v-for="(item, index) in filteredGoodsList" :key="index" class="goods-item">
				<!-- 商品图片 -->
				<image :src="item.picUrl || '/static/default-product.png'" class="goods-image" mode="aspectFill"
					@click="goToDetail(item)" />
				<!-- 商品信息 -->
				<view class="goods-info">
					<text class="goods-name">{{item.name}}</text>
					<text class="goods-brief">{{item.brief}}</text>
					<text class="goods-price">¥{{item.counterPrice}}</text>
					<!-- 操作按钮 -->
					<view class="action-buttons">
						<button class="edit-btn" @tap.stop="editGoods(item)">编辑</button>
						<button class="delete-btn" @tap.stop="deleteGoods(item)">删除</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view v-if="filteredGoodsList.length === 0" class="empty-state">
			<text class="tn-icon-shop" style="font-size: 100rpx; color: #999;"></text>
			<text class="empty-text">{{searchKeyword ? '未找到相关商品' : '暂无发布的商品'}}</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				goodsList: [],
				loading: false,
				searchKeyword: '',
				statusBarHeight: 0
			}
		},

		computed: {
			filteredGoodsList() {
				if (!this.searchKeyword) {
					return this.goodsList;
				}
				const keyword = this.searchKeyword.toLowerCase();
				return this.goodsList.filter(item => 
					item.name.toLowerCase().includes(keyword)
				);
			}
		},

		onLoad() {
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight;
			this.loadMyPublishedGoods();
		},

		// 页面显示时触发
		onShow() {
			this.loadMyPublishedGoods();
		},

		methods: {
			handleReturn() {
				uni.navigateBack({
					delta: 1
				});
			},

			async loadMyPublishedGoods() {
				// 如果正在加载，则不重复加载
				if (this.loading) {
					return;
				}

				const userInfo = uni.getStorageSync('userInfo');
				if (userInfo == undefined || userInfo.id === undefined) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/Information/login/login'
						});
					}, 1500);
					return;
				}

				this.loading = true;
				uni.showLoading({
					title: '加载中...'
				});

				try {
					const res = await uni.request({
						url: this.baseUrl + '/wx/publish/list',
						method: 'GET',
						data: {
							userId: userInfo.id
						}
					});

					console.log('获取发布商品响应:', res.data);

					if (res.data.errno === 0) {
						this.goodsList = res.data.data.list || [];
						if (this.goodsList.length === 0) {
							uni.showToast({
								title: '暂无发布的商品',
								icon: 'none',
								duration: 2000
							});
						}
					} else {
						uni.showToast({
							title: res.data.errmsg || '获取数据失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取发布商品列表失败:', error);
					uni.showToast({
						title: '获取商品列表失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
					uni.hideLoading();
				}
			},

			goToDetail(item) {
				const userInfo = uni.getStorageSync('userInfo');
				uni.navigateTo({
					url: `/pages/index/productDetails/productDetails?id=${item.id}&userId=${userInfo.id}`
				});
			},

			// 编辑商品
			editGoods(item) {
				uni.navigateTo({
					url: `/pages/Information/subpage/editGoods?id=${item.id}`,
					fail: (err) => {
						console.error('跳转编辑页失败:', err);
						uni.showToast({
							title: '跳转失败',
							icon: 'none'
						});
					}
				});
			},

			// 删除商品
			deleteGoods(item) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这个商品吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								const userInfo = uni.getStorageSync('userInfo');
								const response = await uni.request({
									url: this.baseUrl + `/wx/publish/delete/${userInfo.id}`,
									method: 'POST',
									data: {
										goodsId: item.id
									}
								});
								console.log(response);
								if (response.data.errno === 0) {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});
									// 重新加载商品列表
									this.loadMyPublishedGoods();
								} else {
									uni.showToast({
										title: response.data.errmsg || '删除失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('删除商品失败:', error);
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			// 处理搜索
			handleSearch() {
				// 触发搜索时可以添加其他逻辑
				console.log('搜索关键词:', this.searchKeyword);
			},

			// 清除搜索
			clearSearch() {
				this.searchKeyword = '';
			}
		}
	}
</script>

<style>
	.publish-container {
		padding-bottom: 30rpx;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		padding: 10rpx 20rpx;
		background-color: #fff;
		position: fixed;
		width: 100%;
		top: var(--status-bar-height);
		left: 0;
		right: 0;
		z-index: 100;
		height: 88rpx;
		box-sizing: border-box;
	}

	.nav-placeholder {
		width: 100%;
		height: calc(88rpx + var(--status-bar-height));
	}

	.title {
		margin-left: 20rpx;
		font-size: 32rpx;
		font-weight: bold;
	}

	.goods-list {
		padding: 20rpx;
	}

	.goods-item {
		display: flex;
		padding: 20rpx;
		margin-bottom: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.goods-image {
		width: 200rpx;
		height: 200rpx;
		border-radius: 8rpx;
	}

	.goods-info {
		flex: 1;
		margin-left: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.goods-name {
		font-size: 28rpx;
		font-weight: bold;
	}

	.goods-brief {
		font-size: 24rpx;
		color: #666;
		margin: 10rpx 0;
	}

	.goods-price {
		font-size: 32rpx;
		color: #ff4400;
		font-weight: bold;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}

	.empty-text {
		margin-top: 20rpx;
		font-size: 28rpx;
		color: #999;
	}

	.action-buttons {
		display: flex;
		justify-content: flex-end;
		margin-top: 10rpx;
		gap: 20rpx;
	}

	.edit-btn,
	.delete-btn {
		padding: 10rpx 20rpx;
		font-size: 24rpx;
		border-radius: 8rpx;
		border: none;
		color: white;
	}

	.edit-btn {
		background-color: #4CAF50;
	}

	.delete-btn {
		background-color: #f44336;
	}

	.edit-btn:active,
	.delete-btn:active {
		opacity: 0.8;
	}

	/* 搜索框样式 */
	.search-box {
		padding: 20rpx;
		background-color: #fff;
	}

	.search-input-box {
		display: flex;
		align-items: center;
		background-color: #f5f5f5;
		border-radius: 30rpx;
		padding: 10rpx 20rpx;
	}

	.search-input {
		flex: 1;
		height: 60rpx;
		margin: 0 20rpx;
		font-size: 28rpx;
	}

	.tn-icon-search, .tn-icon-close {
		font-size: 36rpx;
		color: #666;
	}

	.tn-icon-close {
		padding: 10rpx;
	}
</style>